import * as THREE from 'three'
import camera from '../camera'

export default class AlarmSprite {
  constructor(type = '火警', position = { x: -1.8, z: 3 }, color = 0xffff00) {
    const textureLoader = new THREE.TextureLoader()

    const typeObj = {
      火警: './textures/fire.png',
      电力: './textures/dianli.png',
      治安: './textures/jingcha.png',
    }

    const map = textureLoader.load(typeObj[type])
    this.material = new THREE.SpriteMaterial({ map: map, depthTest: false, transparent: true })

    this.mesh = new THREE.Sprite(this.material)

    // 设置位置
    this.mesh.position.set(position.x, 4, position.z)

    this.fns = []

    this.raycaster = new THREE.Raycaster()
    this.mouse = new THREE.Vector2()

    // 事件监听
    window.addEventListener('click', e => {
      this.mouse.x = (e.clientX / window.innerWidth) * 2 - 1
      this.mouse.y = -(e.clientY / window.innerHeight) * 2 + 1

      this.raycaster.setFromCamera(this.mouse, camera)

      e.mesh = this.mesh
      e.alarm = this

      const intersects = this.raycaster.intersectObject(this.mesh)
      if (intersects.length > 0) this.fns.forEach(fn => fn(e))
    })
  }

  onClick(fun) {
    this.fns.push(fun)
  }

  remove() {
    this.mesh.remove()
    this.mesh.removeFromParent()
    this.mesh.geometry.dispose()
    this.mesh.material.dispose()
  }
}
